package com.yobol.jgrowth.listener;

import com.yobol.jgrowth.domain.User;
import com.yobol.jgrowth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

/**
 * Listen Session Association
 *
 * @author yobol
 * @create 2018-03-26 16:40
 **/
@WebListener
public class UserSessionListener implements HttpSessionListener {

    @Autowired
    private UserService userService;
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("Session is created");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        User user = new User();
        HttpSession session = httpSessionEvent.getSession();
        user.setName((String)session.getAttribute("username"));
        user.setLatestOnlineTime(new Date(System.currentTimeMillis()));
        userService.loginOut(user);
        System.out.println("Session is destroyed");
    }
}
